package com.hw.nio.selector;



import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

/**
 * @author 车宏伟
 * @date 2021/1/14 22:55
 * TCP 多路复用实现
 */
public class ServerSocketSelector {

    @Test
    public void tcpSelector() throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(6666));
        serverSocketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        // 捕捉创建连接事件
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true){
            int count = selector.select();
            if(count > 0){
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()){

                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();
                    if(selectionKey.isAcceptable()){
                        System.out.println("客户端已连接给一个读取事件");
                        selectionKey.interestOps(SelectionKey.OP_READ);
                    }else if (selectionKey.isReadable()){
                        SocketChannel channel = (SocketChannel) selectionKey.channel();
                        channel.read(buffer);
                        buffer.flip();
                        System.out.println("读取到客户端的连接了");
                        System.out.println(buffer.get(new byte[buffer.remaining()]));
                        selectionKey.interestOps(SelectionKey.OP_WRITE);
                    }else if(selectionKey.isWritable()){
                        SocketChannel channel = (SocketChannel) selectionKey.channel();
                        channel.write(ByteBuffer.wrap(String.valueOf(System.currentTimeMillis()).toString().getBytes(StandardCharsets.UTF_8)));
                    }
                }
            }

        }
    }
}
